package com.boot.hospital.score.core.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.boot.hospital.score.common.wrapper.ResponseWrapper;
import com.boot.hospital.score.core.excelEntity.CadresImportVO;
import com.boot.hospital.score.core.excelEntity.ExpertImportVO;
import com.boot.hospital.score.dao.entity.Score;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@CrossOrigin(origins = "*")
@Slf4j

/**
 * 公共使用接口类
 */
@PropertySources(value = {@PropertySource(value = {"classpath:important.properties", "classpath:application.properties"},
        encoding = "utf-8")})
@RestController
@RequestMapping("/api/file")
@EnableAutoConfiguration
public class CommonController {

    /**
     * excel表导入专家表
     *
     * @param multipartFile
     * @return
     * @throws Exception
     */
    @ApiOperation("导入专家表")
    @PostMapping("/uploadExpertList")
    public List<ExpertImportVO> uploadExpertFile(@RequestParam("expertFile") MultipartFile multipartFile) throws Exception {
        //new一个模板
        ImportParams params = new ImportParams();
        //设置表格标题行数,默认0，这是读取时会跳过的行数
        params.setTitleRows(0);
        //表头行数,默认1。
        params.setHeadRows(1);
        //开始读取，并用list接收，方便处理
        List<ExpertImportVO> expertResult = ExcelImportUtil.importExcel(multipartFile.getInputStream(), ExpertImportVO.class, params);
        System.out.println(JSONUtil.toJsonStr(expertResult));
        saveExpertList(expertResult);
        return expertResult;
    }

    /**
     * 存取导入的专家名单
     *
     * @param expertResult
     * @return
     */
    @ApiOperation("存取导入的专家名单")
    @PostMapping("saveExpertList")
    public ResponseWrapper<Object> saveExpertList(List<ExpertImportVO> expertResult) {
        ResponseWrapper<Object> responseWrapper = new ResponseWrapper<>();

        System.out.println(expertResult);
        for (ExpertImportVO e : expertResult) {
            // 获取专家名称
            System.out.println(e.getExpertName());
            // 调用sql语句插入到数据库中

        }

        return responseWrapper;
    }


    /**
     * excel表导入专家表
     *
     * @param multipartFile
     * @return
     * @throws Exception
     */
    @ApiOperation("导入考评人员表")
    @PostMapping("/uploadCadresList")
    public List<CadresImportVO> uploadCadresFile(@RequestParam("CadresFile") MultipartFile multipartFile) throws Exception {
        //new一个模板
        ImportParams params = new ImportParams();
        //设置表格标题行数,默认0，这是读取时会跳过的行数
//        params.setTitleRows(0);
//        //表头行数,默认1。
//        params.setHeadRows(1);
        //开始读取，并用list接收，方便处理
        List<CadresImportVO> cadresResult = ExcelImportUtil.importExcel(multipartFile.getInputStream(), CadresImportVO.class, params);
        System.out.println(JSONUtil.toJsonStr(cadresResult));
        saveCadresList(cadresResult);
        return cadresResult;
    }

    /**
     * 存取导入的考评人员名单
     *
     * @param cadresResult
     * @return
     */
    @ApiOperation("存取导入的考评人员名单")
    @PostMapping("saveCadresList")
    public ResponseWrapper<Object> saveCadresList(List<CadresImportVO> cadresResult) {
        ResponseWrapper<Object> responseWrapper = new ResponseWrapper<>();

        System.out.println(cadresResult);
        for (CadresImportVO e : cadresResult) {
            // 获取考评人员名称
            System.out.println(e.getName());
            // 调用sql语句插入到数据库中

        }

        return responseWrapper;
    }

    @PostMapping("exportExcel")
    public void exportExcel(HttpServletResponse response) throws Exception {
        response.setContentType("application/octet-stream;charset=UTF-8");
        String fileNameUtf = URLEncoder.encode("下载文档的名称", "UTF-8").replaceAll("\\+", "%20");
        System.out.println("fileNameUtf:"+fileNameUtf);
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileNameUtf + ".xlsx");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

        //designate template
        String templateFileName = System.getProperty("user.dir") + "/excelTemplate/excel.xlsx";
        System.out.println("templateFileName:"+templateFileName);

        //需填充的数据
        List<Score> scores = new ArrayList<>();
        for(int i = 1;i<=5;i++){
            Score e = new Score();
            e.setCadresId(i+"");
            e.setReviewId(i);
            e.setExpertId(""+i);
            e.setCadresId(""+i);
            e.setScore(i*10+i+"");
            scores.add(e);
        }
//        Map<String, Object> map = MapUtils.newHashMap();

        //往response 的输出流中写入数据
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(templateFileName).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();

        //写入materils中的数据
        excelWriter.fill(scores, fillConfig, writeSheet);

//        excelWriter.fill(map, writeSheet);

        //关闭流

        excelWriter.finish();

    }

}
